package com.py.credit.controller;

import com.py.credit.common.Page;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.CswhObj;
import com.py.credit.entity.GzObj;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CjGzTableFieldEnum;
import com.py.credit.entity.enums.JlGzTableFieldEnum;
import com.py.credit.entity.enums.ResourceTemplateFieldsEnum;
import com.py.credit.service.CswhService;
import com.py.credit.service.GzService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.TemplateForLhjcService;
import com.py.credit.utils.MapCache;
import com.py.framework.core.helper.HttpServletHelper;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 联合奖惩规则controller
 */
@RestController
@RequestMapping(value = "/templateForLhjc")
public class TemplateForLhjcController {

    private final static String FRONT_TABLE_ID = "templateForLhjc";


    @Autowired
    private TemplateForLhjcService templateForLhjcService;

    @Autowired
    private CswhService cswhService;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Value("${absolutepath}")
    private String absolutepath;

    /**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r=new RestServiceResult<List<OptionalColumn>>();
		try{
			r=new RestServiceResult<List<OptionalColumn>>(ResourceTemplateFieldsEnum.getOptionalColumns());
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}
	
	
	/**
	 * @api {get} /dataClean/getTableList.json 获取表规则列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 表规则管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 * {"code":0,"msg":null,"count":2,"data":[{"rule_package":"1222","rule_desc":"122222","rule_name":"1","rule_method":"123","id":22,"time":"2018-04-23","managerName":"超级管理员"},{"rule_package":"555","rule_desc":"5555","rule_name":"555","rule_method":"555","id":35,"time":"2018-04-26","managerName":"超级管理员"}]}
	 * 
	 */
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,HttpServletRequest request) {
		    RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
		    // 获取当前用户信息
		RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementCountController#getAchievementCount", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_"  + FRONT_TABLE_ID);
		String[] additionalColumns = {"id"};
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceTemplateFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
//				condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
	    try{
			List<Map> tableList = templateForLhjcService.getByConditionForPage(showColumns,additionalColumns,condition, page);
			result=new RestServiceResult<List<Map>>(page.getTotalCount(), tableList);
		}catch(Exception e){
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常！");
		}
        return result;
		

	}
	
	
	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r=new RestServiceResult<List<OptionalColumn>>();
		try{
			r=new RestServiceResult<List<OptionalColumn>>(ResourceTemplateFieldsEnum.getAdvancedConditionColumns());
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
		      HttpServletRequest request) {
		    RestServiceResult<String> result = new RestServiceResult<String>();
		    // 获取当前用户信息
		    RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		    SysUser userInfo = null;
		    if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
		      userInfo = user.getData();
		      if (null == userInfo || userInfo.getId() <= 0) {
		        result.setCode(RestServiceResult.CODE_UNKNOW);
		        result.setMsg("系统异常，请稍后再试！");
		        ExceptionLogger.error("BatchLogController#addShowColunms", "未获取到当前用户信息！");
		        return result;
		      }

		      String column = StringUtils.join(columns, ",");
		      //column = column;
		      MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		    } else {
		      result.setCode(user.getCode());
		      result.setMsg(user.getMsg());
		      return result;
		    }
		    return result;
		  }
	
	
	
	

	
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/selectMbCode.json")
	public RestServiceResult<List<Map<String, Object>>> selectMbCode() {
		RestServiceResult<List<Map<String, Object>>> r=new RestServiceResult<List<Map<String, Object>>>();
		String name=templateForLhjcService.selectDb();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<List<Map<String, Object>>>(templateForLhjcService.selectMbCode(name));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/selectOne.json")
	public RestServiceResult<Map> selectOne(@RequestParam(value = "id", required = true) int id) {
		RestServiceResult<Map> r=new RestServiceResult<Map>();
		String name=templateForLhjcService.selectDb();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<Map>(templateForLhjcService.selectOne(id));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/selectSameName.json")
	public RestServiceResult<Integer> selectSameName(@RequestParam(value = "name", required = true) String name) {
		RestServiceResult<Integer> r=new RestServiceResult<Integer>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<Integer>(templateForLhjcService.selectSameName(name));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/selectSameStatus.json")
	public RestServiceResult<Integer> selectSameStatus(@RequestParam(value="id",required=false,defaultValue="0") Integer id,@RequestParam(value = "status", required = true) String status) {
		RestServiceResult<Integer> r=new RestServiceResult<Integer>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<Integer>(templateForLhjcService.selectSameStatus(id,status));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/selectOtherSameName.json")
	public RestServiceResult<Integer> selectOtherSameName(@RequestParam(value = "name", required = true) String name,@RequestParam(value = "id", required = true) int id) {
		RestServiceResult<Integer> r=new RestServiceResult<Integer>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<Integer>(templateForLhjcService.selectOtherSameName(id, name));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	
	
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/startEnable.json")
	public RestServiceResult<Object> startEnable(@RequestParam(value = "id", required = true) int id) {
		RestServiceResult<Object> r=new RestServiceResult<Object>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			templateForLhjcService.startEnable(id);
			r.setCode(RestServiceResult.CODE_SUCCESS);
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/endEnable.json")
	public RestServiceResult<Object> endEnable(@RequestParam(value = "id", required = true) int id) {
		RestServiceResult<Object> r=new RestServiceResult<Object>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			templateForLhjcService.endEnable(id);
			r.setCode(RestServiceResult.CODE_SUCCESS);
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/del.json")
	public RestServiceResult<Object> del(@RequestParam(value = "ids", required = true) String ids) {
		RestServiceResult<Object> r=new RestServiceResult<Object>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			templateForLhjcService.del(ids);
			r.setCode(RestServiceResult.CODE_SUCCESS);
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/countEnable.json")
	public RestServiceResult<Integer> countEnable(@RequestParam(value = "ids", required = true) String ids) {
		RestServiceResult<Integer> r=new RestServiceResult<Integer>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			r=new RestServiceResult<Integer>(templateForLhjcService.countEnable(ids));
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/add.json")
	public RestServiceResult<Object> add(@Param(value = "name") String name, @Param(value = "status")String status,@Param(value = "content")String content) {
		RestServiceResult<Object> r=new RestServiceResult<Object>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			templateForLhjcService.add(name, status, content);
			r.setCode(RestServiceResult.CODE_SUCCESS);
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
	
	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/modify.json")
	public RestServiceResult<Object> modify(@Param(value = "id")int id, @Param(value = "name")String name,@Param(value = "isDel")String isDel, @Param(value = "status")String status, @Param(value = "content")String content) {
		RestServiceResult<Object> r=new RestServiceResult<Object>();
    	//List<Map<String, Object>> template = templateForLhjcService.selectMbCode(name);
		try{
			templateForLhjcService.modify(id, name,isDel, status, content);
			r.setCode(RestServiceResult.CODE_SUCCESS);
		}catch(Exception e){
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("数据清洗查询详细异常异常");
			ExceptionLogger.error("数据清洗查询详细异常异常！", e.getMessage(), e);
		}
		return r;
	}
}
